package net.wanho.systemSettings.dao.impl;

import net.wanho.commons.dao.impl.BaseDAOImpl;
import net.wanho.commons.exception.DAOException;
import net.wanho.commons.exception.DataAccessException;
import net.wanho.systemSettings.dao.MenuDAO;
import net.wanho.systemSettings.po.Menu;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MenuDAOImpl extends BaseDAOImpl<Menu> implements MenuDAO {
    @Override
    public List<Menu> selectByCond(Map<String, String> condMap) throws DAOException {
        try {
            String sql = "SELECT\n" +
                    "  s.MENU_ID           menuId,\n" +
                    "  s.MENU_NAME         menuName,\n" +
                    "  s.MENU_URL          menuUrl,\n" +
                    "  s.PICTURES          pictures,\n" +
                    "  s.STATUS            STATUS,\n" +
                    "  s.CREATE_TIME       createTime,\n" +
                    "  s.UPDATE_TIME       updateTime,\n" +
                    "  s.PARENT_MENU_ID    parentMenuId\n" +
                    "FROM menu s\n" +
                    "WHERE 1 = 1 ";
            //动态拼接SQL
            StringBuffer sb = new StringBuffer(sql);
            //条件无效  或者 没有条件
            boolean isCond = condMap == null || condMap.isEmpty();
            //创建集合 存放 动态参数值 ？ 替换的值
            List<Object> condParamValueList = new ArrayList<>();
            //有效条件
            if (!isCond && StringUtils.isNotEmpty(condMap.get("name"))) {
                sb.append(" AND MENU_NAME like ?") ;
                condParamValueList.add("%"+condMap.get("name")+"%") ;
            }
            //根据职位id 查询当前职位关联的所有的菜单
            if (!isCond && StringUtils.isNotEmpty(condMap.get("positionId"))) {
                sb.append(" AND s.MENU_ID IN(SELECT\n" +
                        "                       MENU_ID\n" +
                        "                     FROM position_menu_relations\n" +
                        "                     WHERE POSITION_ID = ?)") ;
                condParamValueList.add(condMap.get("positionId")) ;
            }
            Object[] params = condParamValueList.toArray();
            return super.queryForList(sb.toString(), params);
        } catch (DataAccessException e) {
            e.printStackTrace();
            throw new DAOException(e.getMessage());
        }
    }
}
